前端analysis | 知其所以然

reactjs ai大模型单元测试

2025-05-25

LLM

✅ 一、你要测试的典型对象

举例:你有个 React Hook 或 service 用来调用大模型 API:

1
2
3
4
5
6
7
8
9
10
// src/services/llmService.ts
export async function callLLM(prompt: string): Promise<string> {
const response = await fetch('/api/llm', {
method: 'POST',
body: JSON.stringify({ prompt }),
headers: { 'Content-Type': 'application/json' },
});
const data = await response.json();
return data.result;
}

目标是为这个函数自动生成测试。


🛠️ 二、推荐的技术栈

目标 工具
单元测试框架 Jest
模拟 HTTP 请求 msw
自动生成测试代码(AI 辅助) ChatGPT、CodiumAI、TestGPT

🔁 三、用 AI 自动生成测试用例(方式)

✅ 方法 1:用 ChatGPT 自动生成测试

你可以把你的函数贴进来,并让 ChatGPT 为你写 Jest 测试。例如:

1
2
3
4
5
6
7
8
9
10
11
为以下函数写一个 Jest 单元测试,模拟 API 返回和异常:

export async function callLLM(prompt: string): Promise<string> {
const response = await fetch('/api/llm', {
method: 'POST',
body: JSON.stringify({ prompt }),
headers: { 'Content-Type': 'application/json' },
});
const data = await response.json();
return data.result;
}

➡️ ChatGPT 会给出类似这样的测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// __tests__/llmService.test.ts
import { callLLM } from '../services/llmService';

global.fetch = jest.fn();

describe('callLLM', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should return result when API responds successfully', async () => {
const mockResponse = { result: 'Hello, world!' };
(fetch as jest.Mock).mockResolvedValue({
json: () => Promise.resolve(mockResponse),
});

const result = await callLLM('Hi');
expect(result).toBe('Hello, world!');
});

it('should throw error if fetch fails', async () => {
(fetch as jest.Mock).mockRejectedValue(new Error('Network error'));

await expect(callLLM('Hi')).rejects.toThrow('Network error');
});
});

🤖 方法 2:集成 AI 测试自动化工具(前沿方向)

✨ 1. CodiumAI(自动补全测试)

  • VSCode 插件
  • 根据函数生成 Jest 测试模板
  • 支持 TS、React、Node

📦 安装:

1
code --install-extension Codium.codiumai

官网:https://www.codium.ai


✨ 2. TestGPT(ChatGPT 自动生成测试)

可以结合 ChatGPT API 或 OpenAI 插件,传入代码片段,返回 Jest 测试。


📦 四、为 React Component 生成 LLM Mock 测试(完整流程)

假设你有一个组件,输入 prompt 调用大模型接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// PromptInput.tsx
import React, { useState } from 'react';
import { callLLM } from './services/llmService';

export const PromptInput = () => {
const [prompt, setPrompt] = useState('');
const [result, setResult] = useState('');

const handleSubmit = async () => {
const res = await callLLM(prompt);
setResult(res);
};

return (
<div>
<input value={prompt} onChange={(e) => setPrompt(e.target.value)} />
<button onClick={handleSubmit}>Submit</button>
<p>{result}</p>
</div>
);
};

你可以写一个自动化测试这样测试它(用 @testing-library/react):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { render, screen, fireEvent } from '@testing-library/react';
import { PromptInput } from './PromptInput';
import * as llmService from './services/llmService';

jest.mock('./services/llmService');

test('renders input and displays LLM response', async () => {
(llmService.callLLM as jest.Mock).mockResolvedValue('Mock response');

render(<PromptInput />);
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Hi' } });
fireEvent.click(screen.getByText('Submit'));

const result = await screen.findByText('Mock response');
expect(result).toBeInTheDocument();
});

🧩 五、可选:测试生成平台一键生成

  • CodiumAI
  • GitHub Copilot Labs
  • TestGPT(社区项目)

✅ 总结:React + LLM 测试自动化建议

类型 推荐做法
LLM 调用函数测试 用 Jest 单测,mock fetch 或 axios
React 组件测试 @testing-library/react + Jest
自动生成测试代码 ChatGPT、CodiumAI、Copilot Labs、TestGPT 等辅助
稳定测试建议 使用 msw 作为 mock server 来模拟 LLM 响应

Tags: reactjs
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏